package com.boot.service.impl;

import com.boot.model.AuthenticationRequest;
import com.boot.model.UserDto;
import com.boot.service.AuthenticationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author Chunsheng.Zhang
 * @date 2021/4/8 10:18
 * @description : TODO
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService {


    @Override
    public UserDto authentication(AuthenticationRequest authenticationRequest) {
        //认证逻辑

        if(authenticationRequest == null
                || StringUtils.isEmpty(authenticationRequest.getUsername())
                || StringUtils.isEmpty(authenticationRequest.getPassword())){
            throw new RuntimeException("账号或者密码为空");
        }


        UserDto userDto = getUserByName(authenticationRequest.getUsername());
        if(userDto == null){
            throw new RuntimeException("该账号不存在");
        }

        if(!authenticationRequest.getPassword().equals(userDto.getPassword())){
            throw new RuntimeException("密码错误");
        }


        return userDto;
    }








    //模拟数据库
    private Map<String,UserDto> userMap = new HashMap();
    //静态块
    {
        Set<String> authorities1 = new HashSet<>();
        authorities1.add("m1");//m1是权限标识符，默认与/user/m1 对应
        Set<String> authorities2 = new HashSet<>();
        authorities2.add("m2");//m2是权限标识符，默认与/user/m2 对应


        userMap.put("zs",new UserDto(null,"zs","zhangsan@1234","zhangsan","18792943389",authorities1));
        userMap.put("lisi",new UserDto(null,"ls","lisi@1234","ls","18792943389",authorities2));
    }

    private UserDto getUserByName(String username){
        return userMap.get(username);
    }
}
